package com.qk.manangement.controller;

import cn.hutool.core.util.StrUtil;
import com.qk.common.response.PageResult;
import com.qk.common.response.Result;
import com.qk.entity.pojo.Customer;
import com.qk.manangement.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * 客户列表查询
     */
    @RequestMapping
    public Result list(String phone,String name,Integer channel,Integer subject,
                       @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer pageSize
                       ) {
        PageResult list = customerService.list(phone, name, channel, subject, page, pageSize);
        return Result.success(list);

    }

    /**
     * 添加客户
     */
    @PostMapping
    public Result add(@RequestBody Customer customer) {
        //参数判断
        if (StrUtil.isBlank(customer.getPhone()) || StrUtil.isBlank(customer.getName())) {
            return Result.error("参数错误");
        }
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        boolean save = customerService.save(customer);
        return save ? Result.success() : Result.error(  "添加失败");
    }


    /**
     * 根据id查询客户
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Customer customer = customerService.getById(id);
        return Result.success(customer);
    }

    /**
     * 修改客户
     */
    @PutMapping
    public Result update(@RequestBody Customer customer) {
        customer.setUpdateTime(LocalDateTime.now());
        boolean update = customerService.updateById(customer);
        return update ? Result.success() : Result.error("修改失败");
    }
}
